﻿Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.Runtime.Serialization
Imports System.IO

REM version 5.0.0.0

<ServiceContract(Namespace:="")>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class AFSBilderUpDownload

    <OperationContract()>
    Public Function UploadFile(ByVal file As UploadFileInformation) As ReturnType
        Dim retval As New ReturnType

        Dim filePath = Path.Combine(MainPath, file.Filename)

        If System.IO.File.Exists(filePath) Then
            retval.FileAlreadyExists = True
            retval.hasError = False
            retval.NoSuchFileFound = False
            retval.Succeed = True
            retval.Errors = Nothing
        Else
            Try
                Using targetStream = New FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)
                    targetStream.Write(file.FileStream, 0, file.FileStream.Length)
                    targetStream.Flush()
                End Using
                retval.FileAlreadyExists = False
                retval.Errors = Nothing
                retval.hasError = False
                retval.Succeed = True
            Catch ex As Exception
                retval.hasError = True
                retval.Succeed = False
                retval.Errors = ex
                retval.NoSuchFileFound = False
                retval.FileAlreadyExists = False
            End Try
        End If


        Debug.WriteLine(file.FileStream.Length)

        

        Return retval
    End Function

    <OperationContract>
    Public Function PreCheckFile(ByVal name As String) As Boolean
        Dim listof = prefilterFiles()
        Dim a = From b In listof
                Where b.Name = name
                Select b

        If a.Count = 0 Then
            Return False
        Else
            Return True
        End If
    End Function


    <OperationContract>
    Public Function DownloadFile(ByVal name As String) As UploadFileInformation
        Dim filePath = Path.Combine(MainPath, name)
        Dim retval As New UploadFileInformation

        retval.Filename = name
        '  Dim filestr = New System.IO.FileStream("C:\Users\AFSWindows8\Documents\Visual Studio 2012\Projects\AFS.BackyardService\AFS.MandatBackyardService\Global.asax", IO.FileMode.Open)
        If System.IO.File.Exists(filePath) Then
            Try
                retval.FileStream = System.IO.File.ReadAllBytes(filePath)
                retval.hasError = False
                retval.Exceptions = Nothing
            Catch ex As Exception
                retval.FileStream = Nothing
                retval.hasError = True
                retval.Exceptions = ex
            End Try
        Else
            retval.FileStream = Nothing
            retval.hasError = True
            retval.Exceptions = New Exception("NoSuchFileFound")
        End If

        Debug.WriteLine("Download... " & retval.FileStream.Length)
        Return retval
    End Function


    <OperationContract>
    Public Function DownloadFileList(ByVal namelist As List(Of String)) As List(Of UploadFileInformation)
        Dim retval As New List(Of UploadFileInformation)
        For Each a In namelist
            retval.Add(Me.DownloadFile(a))
        Next
        Return retval
    End Function

    <OperationContract>
    Public Function EnumerateAllFiles() As List(Of String)
        Dim filescontainer As New System.IO.DirectoryInfo(MainPath)
        Dim retval As New List(Of String)
        Dim possibleExtensions As New List(Of String) From {".jpg", ".jpeg", ".bmp", ".gif", ".png"}
        For Each File In filescontainer.GetFiles
            If possibleExtensions.Contains(File.Extension) Then
                retval.Add(File.Name)
            End If
        Next
        Return retval
    End Function

    Private Function prefilterFiles() As List(Of FileInfo)
        Dim filescontainer As New System.IO.DirectoryInfo(MainPath)
        Dim possibleExtensions As New List(Of String) From {".jpg", ".jpeg", ".bmp", ".gif", ".png"}
        Dim retval As New List(Of FileInfo)
        For Each File In filescontainer.GetFiles
            If possibleExtensions.Contains(File.Extension) Then
                retval.Add(File)
            End If
        Next
        Return retval
    End Function


    <OperationContract>
    Public Function SearchForFiles(ByVal Datum As String, ByVal uhrzeitv As String, ByVal uhrzeitb As String) As List(Of UploadFileInformation)
        Dim query As IEnumerable(Of FileInfo) = prefilterFiles()

        If Datum <> "" Then
            query = query.Where(Function(a As FileInfo)
                                    If Split(a.Name, "-")(0).Equals(Datum) Then
                                        Return True
                                    Else
                                        Return False
                                    End If
                                End Function)
        End If

        If uhrzeitv <> "" Then
            If uhrzeitv.Contains(":") Then
                uhrzeitv = Replace(uhrzeitv, ":", ".")
            End If
            query = query.Where(Function(a As FileInfo)
                                    If CDate(Split(a.Name, "-")(1)) >= CDate(uhrzeitv) Then
                                        Return True
                                    Else
                                        Return False
                                    End If
                                End Function)
        End If

        If uhrzeitb <> "" Then
            If uhrzeitb.Contains(":") Then
                uhrzeitb = Replace(uhrzeitb, ":", ".")
            End If
            query = query.Where(Function(a As FileInfo)
                                    If CDate(Split(a.Name, "-")(1)) <= CDate(uhrzeitb) Then
                                        Return True
                                    Else
                                        Return False
                                    End If
                                End Function)
        End If

        Dim retval As New List(Of UploadFileInformation)
        For Each a In query
            '  retval.Add(DownloadFile(a.Name))
            Dim file = DownloadFile(a.Name)
            If file.hasError = False Then
                retval.Add(file)
            End If
        Next
        Return retval
    End Function
    ' Hier weitere Vorgänge hinzufügen und kennzeichnen mit <OperationContract()>

    <OperationContract>
    Function DeleteFile(ByVal name As String) As ReturnType
        Dim retval As New ReturnType
        Dim listof = prefilterFiles()
        Dim a As IEnumerable(Of FileInfo)

        If name = "" Then
            a = prefilterFiles()
        Else
            a = From b In listof
                Where b.Name = name
                Select b
        End If

        Try
            For Each c In a
                c.Delete()
            Next
            retval.Errors = Nothing
            retval.hasError = False
            retval.Succeed = True
        Catch ex As Exception
            retval.Errors = ex
            retval.hasError = True
            retval.Succeed = False
        End Try
        Return retval
    End Function

    <OperationContract>
    Function DeleteRangeOfFiles(ByVal nameslist As List(Of String)) As Boolean
        Dim retval As New ReturnType
        Dim listof = prefilterFiles()

        Try
            For Each a In nameslist
                Dim b = From c In listof
                        Where c.Name = a
                        Select c

                For Each c In b
                    c.Delete()
                Next
            Next
            Return True
        Catch
            Return False
        End Try
    End Function

End Class


<DataContract>
<ServiceKnownType(GetType(UploadFileInformation))>
Public Class UploadFileInformation
    <DataMember>
    Public Property Filename As String

    <DataMember>
    Public Property FileStream As Byte()

    <DataMember>
    Public Property hasError As Boolean

    <DataMember>
    Public Property Exceptions As Exception
End Class

<DataContract>
<ServiceKnownType(GetType(ReturnType))>
Public Class ReturnType
    <DataMember>
    Public Property hasError As Boolean

    <DataMember>
    Public Property Errors As Exception

    <DataMember>
    Public Property Succeed As Boolean

    <DataMember>
    Public Property FileAlreadyExists As Boolean

    <DataMember>
    Public Property NoSuchFileFound As Boolean
End Class